package com.ycsj.goldmedalnewconcept.fragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.activity.LoginActivity;
import com.ycsj.goldmedalnewconcept.bean.HomeWorkRespons;
import com.ycsj.goldmedalnewconcept.bean.TestSecondResp;
import com.ycsj.goldmedalnewconcept.bean.WordSecondListInfo;
import com.ycsj.goldmedalnewconcept.bean.WordSecondResq2;
import com.ycsj.goldmedalnewconcept.bean.mineBasicInfoResp2;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.R;

/**
 * 首页fragment ViewPager tab
 * 学单词
 * @author dewyze
 *
 */

@SuppressLint("NewApi")
public class PreviewFragment extends BaseFragment implements OnClickListener{
	
	private static final String TAG = "PreviewFragment";
	private Activity mActivity;
	private TextView mMsgTv;
	private String mMsgName;
	private ImageView iv_home01;
	private ImageView iv_home02;
	private ImageView iv_home03;
	private ImageView iv_home04;
	private Button bt_homework;
//	private HeartLayout mHeartLayout;
    private Timer mTimer ;
	public void setMsgName(String msgName) {
		this.mMsgName = msgName;
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.mActivity = activity;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_home_tab, container, false);
		mTimer = new Timer();
//    	if(SPUtils.getBoolean(getActivity(), ConfigConstant.IS_LOGIN_ON)){
//    		final Handler handler=new Handler();
//    	OkHttpClient mOkHttpClient = new OkHttpClient();
//		//创建一个Request
//		final Request request = new Request.Builder()
//		                .url("http://m.moregolden.com:8080/User_Manage/UserOnline/InitUserOnlineBegin_2.aspx?account="+SPUtils.getString(getActivity(),ConfigConstant.USERNAME)+"&client=android"+"&isinitbegintime=0")
//		                .build();
//		//new call
//				Call call = mOkHttpClient.newCall(request); 
//				//请求加入调度
//						call.enqueue(new Callback() {
//							
//							@Override
//							public void onResponse(Response response) throws IOException {
//								// TODO Auto-generated method stub
//								String json = response.body().string();
//								Log.i("testtime", json);
//								Gson gson = new Gson();
////								// 2 使用gson对象的方法
//								if("1".equals(gson.fromJson(json, HomeWorkRespons.class).testflag)){
//
////									Toast.makeText(getActivity(), "haveHomeWork", 0).show();
//
//									
//									handler.postDelayed(new Runnable() {
//										
//										@Override
//										public void run() {
//											// TODO Auto-generated method stub
//											bt_homework.setVisibility(View.VISIBLE);
//											mHeartLayout.setVisibility(View.VISIBLE);
//											
//										}
//									}, 100);
//									 mTimer.scheduleAtFixedRate(new TimerTask() {
//								            @Override
//								            public void run() {
//								                mHeartLayout.post(new Runnable() {
//								                    @Override
//								                    public void run() {
////								                        mHeartLayout.addHeart(randomColor());
//								                    	Random random=new Random();
//								                    	int nextInt = random.nextInt(8);
//								                    	mHeartLayout.addHeart2(nextInt);
//								                        
//								                    }
//								                });
//								            }
//								        }, 500, 200);
//								}
//							}
//							
//							@Override
//							public void onFailure(Request arg0, IOException arg1) {
//								// TODO Auto-generated method stub
//								
//							}
//						});
//						
//    	
//    	}
//    	mHeartLayout = (HeartLayout) view.findViewById(R.id.heart_layout);
    	
		return view;
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initViews(view);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initDisplay();
	}
	
	private void initViews(View view) {
//		mMsgTv = (TextView) view.findViewById(R.id.msg_tv);
		iv_home01 = (ImageView) view.findViewById(R.id.iv_home01);
		iv_home02 = (ImageView) view.findViewById(R.id.iv_home02);
		iv_home03 = (ImageView) view.findViewById(R.id.iv_home03);
		iv_home04 = (ImageView) view.findViewById(R.id.iv_home04);
		
//		bt_homework = (Button) view.findViewById(R.id.bt_homework);
//		View iv_person = view.findViewById(R.id.iv_person);
//		ObjectAnimator ot = ObjectAnimator.ofFloat(iv_person, "translationX",-200,180,10,0);
//		ot.setDuration(3000);
//		ot.start();
		
//		bt_homework.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent(getActivity(),HomeWorkActivity.class);
//				startActivity(intent);
//				  getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
//				
//			}
//		});
		Log.e("test",  "haveHomeWork"+SPUtils.getString(getActivity(), "haveHomeWork"));
//		if("1".equals(SPUtils.getString(getActivity(), "haveHomeWork"))&&SPUtils.getBoolean(getActivity(), ConfigConstant.IS_LOGIN_ON)){}
	}
	
	private void initDisplay() {
//		mMsgTv.setText(mMsgName + "");
		
//		iv_home01.setOnTouchListener(onTouch);
//		iv_home02.setOnTouchListener(onTouch);
//		iv_home03.setOnTouchListener(onTouch);
//		iv_home04.setOnTouchListener(onTouch);
		iv_home01.setOnClickListener(this);
		iv_home02.setOnClickListener(this);
		iv_home03.setOnClickListener(this);
		iv_home04.setOnClickListener(this);
	}

	@Override
	public String getFragmentName() {
		return TAG;
	}

	
	public OnTouchListener onTouch=new OnTouchListener(){

        private float x1;
		private float y1;
		private float x2;
		private float y2;

		@Override
        public boolean onTouch(View v, MotionEvent event) {
           
            switch(event.getAction()){
                case MotionEvent.ACTION_DOWN:
                	x1 = event.getX(); 
                    y1 = event.getY(); 
                    
                case MotionEvent.ACTION_UP:
                	 x2 = event.getX(); 
                     y2 = event.getY(); 
                     if (Math.abs(x1 - x2) < 6) { 
                         return false;// 距离较小，当作click事件来处理 
                     } 
                     if(Math.abs(y1 - y2) >10){  // 真正的onTouch事件 
                    	 Animation shakeAnim = AnimationUtils.loadAnimation(getActivity(),
         						R.anim.shake);
                     	v.startAnimation(shakeAnim);
                     } 
                 } 
                 return true;// 返回true，不执行click事件 
                	
                	
                	
                	
                	
                	
            
        }
        
        
    };

    public Animation shakeAnimation(int CycleTimes) {
		Animation translateAnimation = new TranslateAnimation(0, 0, -10, 10);
		translateAnimation.setInterpolator(new CycleInterpolator(CycleTimes));
		translateAnimation.setDuration(1000);
		return translateAnimation;
	}

	@Override
	public void onClick(View v) {
		//更新SP保存的主页面的ViewPager的当前显示页面数
				SPUtils.put(getActivity(), ConfigConstant.indecaterNum, 0);
				
		switch (v.getId()) {
		case R.id.iv_home01:
			SPUtils.put(getActivity(), "firstNum", 1);
//			Log.e("test", "iv_home01");
			FragmentTransaction ft = getFragmentManager().beginTransaction();
			PreviewSecondFragment wf = new PreviewSecondFragment();  
                Bundle args=new Bundle();
    			args.putInt("GRADE_ID", 2001);
    			
    			args.putString("GRADE_NAME", "第一级");
    			wf.setArguments(args);
    			ft.replace(R.id.center_layout, wf);
    			ft.addToBackStack(null);
    			ft.commit();
			break;
		case R.id.iv_home02:
			SPUtils.put(getActivity(), "firstNum", 19);
			FragmentTransaction ft2 = getFragmentManager().beginTransaction();
			PreviewSecondFragment wf2 = new PreviewSecondFragment();  
                Bundle args2=new Bundle();
    			args2.putInt("GRADE_ID", 2002);
    			args2.putString("GRADE_NAME", "第二级");
    			wf2.setArguments(args2);
    			ft2.replace(R.id.center_layout, wf2);
    			ft2.addToBackStack(null);
    			ft2.commit();
			break;
		case R.id.iv_home03:
			SPUtils.put(getActivity(), "firstNum", 37);
			FragmentTransaction ft3 = getFragmentManager().beginTransaction();
			PreviewSecondFragment wf3 = new PreviewSecondFragment();  
                Bundle args3=new Bundle();
    			args3.putInt("GRADE_ID", 2003);
    			args3.putString("GRADE_NAME", "第三级");
    			wf3.setArguments(args3);
    			ft3.replace(R.id.center_layout, wf3);
    			ft3.addToBackStack(null);
    			ft3.commit();
			break;
		case R.id.iv_home04:
			SPUtils.put(getActivity(), "firstNum", 55);
			FragmentTransaction ft4 = getFragmentManager().beginTransaction();
			PreviewSecondFragment wf4 = new PreviewSecondFragment();  
                Bundle args4=new Bundle();
    			args4.putInt("GRADE_ID", 2004);
    			args4.putString("GRADE_NAME", "第四级");
    			wf4.setArguments(args4);
    			ft4.replace(R.id.center_layout, wf4);
    			ft4.addToBackStack(null);
    			ft4.commit();
			break;
		default:
			break;
		}
		
	}
	
	
	private ArrayList<WordSecondListInfo> list=new ArrayList<WordSecondListInfo>();
	int unitcount1;
	int unitcount2;
	int unitcount3;
	int unitcount4;
	private RequestCallBack<String> callBack1 = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象
			
//			Log.i("test", json);
			
			Gson gson = new Gson();
//			// 2 使用gson对象的方法
			if("1".equals(gson.fromJson(json, mineBasicInfoResp2.class).result)||"2".equals(gson.fromJson(json, WordSecondResq2.class).RESULTTYPE)){
				Intent intent = new Intent(getActivity(),
						LoginActivity.class);
				startActivity(intent);
			}else{
			TestSecondResp classTestSecondResp = gson.fromJson(json, TestSecondResp.class);
			
			unitcount1=classTestSecondResp.LIST.size();
			}
		}
		@Override
		public void onFailure(HttpException error, String msg) {
			
		}
	};
	private RequestCallBack<String> callBack2 = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象
			
			Log.i("test","asdadadasdasda====="+ json);
			
			Gson gson = new Gson();
//			// 2 使用gson对象的方法
			if("1".equals(gson.fromJson(json, mineBasicInfoResp2.class).result)||"2".equals(gson.fromJson(json, WordSecondResq2.class).RESULTTYPE)){
				Intent intent = new Intent(getActivity(),
						LoginActivity.class);
				startActivity(intent);
			}else{
			TestSecondResp classTestSecondResp = gson.fromJson(json, TestSecondResp.class);
			
			unitcount2=classTestSecondResp.LIST.size();
			}
		}
		@Override
		public void onFailure(HttpException error, String msg) {
			
		}
	};
	private RequestCallBack<String> callBack3 = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象
			
//			Log.i("test", json);
			
			Gson gson = new Gson();
//			// 2 使用gson对象的方法
			if("1".equals(gson.fromJson(json, mineBasicInfoResp2.class).result)||"2".equals(gson.fromJson(json, WordSecondResq2.class).RESULTTYPE)){
				Intent intent = new Intent(getActivity(),
						LoginActivity.class);
				startActivity(intent);
			}else{
			TestSecondResp classTestSecondResp = gson.fromJson(json, TestSecondResp.class);
			
			unitcount3=classTestSecondResp.LIST.size();
			}
		}
		@Override
		public void onFailure(HttpException error, String msg) {
			
		}
	};
	private RequestCallBack<String> callBack4 = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象
			
//			Log.i("test", json);
			
			Gson gson = new Gson();
//			// 2 使用gson对象的方法
			if("1".equals(gson.fromJson(json, mineBasicInfoResp2.class).result)||"2".equals(gson.fromJson(json, WordSecondResq2.class).RESULTTYPE)){
				Intent intent = new Intent(getActivity(),
						LoginActivity.class);
				startActivity(intent);
			}else{
			TestSecondResp classTestSecondResp = gson.fromJson(json, TestSecondResp.class);
			
			unitcount4=classTestSecondResp.LIST.size();
			}
		}
		@Override
		public void onFailure(HttpException error, String msg) {
			
		}
	};
	private RequestCallBack<String> callBack5 = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象
			
			Log.i("testtime", json);
			
			Gson gson = new Gson();
//			// 2 使用gson对象的方法
//			if("1".equals(gson.fromJson(json, HomeWorkRespons.class).testflag)){
//
////				Toast.makeText(getActivity(), "haveHomeWork", 0).show();
//
//				bt_homework.setVisibility(View.VISIBLE);
//				mHeartLayout.setVisibility(View.VISIBLE);
//				 mTimer.scheduleAtFixedRate(new TimerTask() {
//			            @Override
//			            public void run() {
//			                mHeartLayout.post(new Runnable() {
//			                    @Override
//			                    public void run() {
////			                        mHeartLayout.addHeart(randomColor());
//			                    	Random random=new Random();
//			                    	int nextInt = random.nextInt(8);
//			                    	mHeartLayout.addHeart2(nextInt);
//			                        
//			                    }
//			                });
//			            }
//			        }, 500, 200);
//			
//			
//			}
		}
		@Override
		public void onFailure(HttpException error, String msg) {
			
		}
	};
	@Override
	public void onStop() {
		super.onStop();
		
	}
	
	 @Override
	public void onDestroy() {
	        super.onDestroy();
	        if(mTimer!=null){
	        mTimer.cancel();
	        mTimer.purge();
	        mTimer = null;
	        }
	    }
	
}
